package com.happyscan138.makefun;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;


import com.happyscan138.makefun.util.RecordUtil;

import java.io.IOException;
import java.util.UUID;

/**
 * Created by Administrator on 2017/1/6.
 */

public class Record extends AppCompatActivity {
    private Button End;
    private Button btnStart;
    private LinearLayout mDisplayVoiceLayout;
    private ImageView mDisplayVoicePlay;
    private TextView mDisplayVoiceTime;
    private ProgressBar mDisplayVoiceProgressBar;
    private MediaPlayer mMediaPlayer;
    private RecordUtil mRecordUtil;
    private static final int MAX_TIME = 60;
    private static final int MIN_TIME = 2;

    private static final int RECORD_NO = 0;
    private static final int RECORD_ING = 1;
    private static final int RECORD_ED = 2;
    private int mRecord_State = 0;
    private float mRecord_Time;
    private double mRecord_Volume;
    private boolean mPlayState;
    private int mPlayCurrentPosition;
    private static final String PATH = "/sdcard/KaiXin/Record/";
    private String mRecordPath;
    private int mMAXVolume;
    private int mMINVolume;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.record);
        initView();
        setListener();
        init();

    }
    public void initView(){
        btnStart=(Button)findViewById(R.id.StartVoice);
        mDisplayVoiceLayout = (LinearLayout) findViewById(R.id.voice_display_voice_layout);
        mDisplayVoicePlay = (ImageView) findViewById(R.id.voice_display_voice_play);
        mDisplayVoiceProgressBar = (ProgressBar) findViewById(R.id.voice_display_voice_progressbar);
        mDisplayVoiceTime = (TextView) findViewById(R.id.voice_display_voice_time);
        End=(Button)findViewById(R.id.EndVoice);

    }

    private void setListener() {
        btnStart.setOnTouchListener(new View.OnTouchListener() {

            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        if (mRecord_State != RECORD_ING) {
                            mRecord_State = RECORD_ING;
                            mRecordPath = PATH + UUID.randomUUID().toString()
                                    + ".mp3";
                            mRecordUtil = new RecordUtil(mRecordPath);
                            try {
                                mRecordUtil.start();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            new Thread(new Runnable() {

                                public void run() {
                                    mRecord_Time = 0;
                                    while (mRecord_State == RECORD_ING) {
                                        if (mRecord_Time >= MAX_TIME) {
                                            //mRecordHandler.sendEmptyMessage(0);
                                        } else {
                                            try {
                                                Thread.sleep(200);
                                                mRecord_Time += 0.2;
                                                if (mRecord_State == RECORD_ING) {
                                                    mRecord_Volume = mRecordUtil
                                                            .getAmplitude();
                                                   // mRecordHandler.sendEmptyMessage(1);
                                                }
                                            } catch (InterruptedException e) {
                                                e.printStackTrace();
                                            }
                                        }
                                    }
                                }
                            }).start();
                        }
                        break;
                    case MotionEvent.ACTION_UP:
                        if (mRecord_State == RECORD_ING) {
                            mRecord_State = RECORD_ED;
                            try {
                                mRecordUtil.stop();
                                mRecord_Volume = 0;
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            if (mRecord_Time <= MIN_TIME) {
                                Toast.makeText(Record.this, "录制时间太短",
                                        Toast.LENGTH_SHORT).show();
                                mRecord_State = RECORD_NO;
                                mRecord_Time = 0;
                                mDisplayVoiceTime.setText("s");
                                mDisplayVoiceProgressBar.setProgress(0);

                            } else {
                                mDisplayVoiceLayout.setVisibility(View.VISIBLE);
                                mDisplayVoicePlay
                                        .setImageResource(R.drawable.globle_player_btn_play);
                                mDisplayVoiceProgressBar.setMax((int) mRecord_Time);
                                mDisplayVoiceProgressBar.setProgress(0);
                                mDisplayVoiceTime.setText((int) mRecord_Time + "s");

                            }
                        }
                        break;
                }
                return false;
            }
        });
        mDisplayVoicePlay.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                if (mRecordPath==null){
                    Toast.makeText(Record.this,"请先录音",Toast.LENGTH_SHORT).show();
                } else {
                    if (!mPlayState) {
                        mMediaPlayer = new MediaPlayer();
                        try {

                            mMediaPlayer.setDataSource(mRecordPath);
                            mMediaPlayer.prepare();
                            mMediaPlayer.start();
                            new Thread(new Runnable() {

                                public void run() {

                                    mDisplayVoiceProgressBar
                                            .setMax((int) mRecord_Time);
                                    mPlayCurrentPosition = 0;
                                    while (mMediaPlayer.isPlaying()) {
                                        mPlayCurrentPosition = mMediaPlayer
                                                .getCurrentPosition() / 1000;
                                        mDisplayVoiceProgressBar
                                                .setProgress(mPlayCurrentPosition);
                                    }
                                }
                            }).start();
                            mPlayState = true;
                            mDisplayVoicePlay.setImageResource(R.drawable.globle_player_btn_stop);

                            mMediaPlayer
                                    .setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                                        public void onCompletion(MediaPlayer mp) {
                                            mMediaPlayer.stop();
                                            mPlayState = false;
                                            mDisplayVoicePlay
                                                    .setImageResource(R.drawable.globle_player_btn_play);
                                            mPlayCurrentPosition = 0;
                                            mDisplayVoiceProgressBar
                                                    .setProgress(mPlayCurrentPosition);
                                        }
                                    });

                        } catch (IllegalArgumentException e) {
                            e.printStackTrace();
                        } catch (IllegalStateException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    } else {
                        if (mMediaPlayer != null) {
                            if (mMediaPlayer.isPlaying()) {
                                mPlayState = false;
                                mMediaPlayer.stop();
                                mDisplayVoicePlay
                                        .setImageResource(R.drawable.globle_player_btn_play);
                                mPlayCurrentPosition = 0;
                                mDisplayVoiceProgressBar
                                        .setProgress(mPlayCurrentPosition);
                            } else {
                                mPlayState = false;
                                mDisplayVoicePlay
                                        .setImageResource(R.drawable.globle_player_btn_play);
                                mPlayCurrentPosition = 0;
                                mDisplayVoiceProgressBar
                                        .setProgress(mPlayCurrentPosition);
                            }
                        }
                    }
                }
            }
        });

        End.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mRecordPath==null) {
                    Toast.makeText(Record.this,"请先录音",Toast.LENGTH_SHORT).show();
                } else {
                    Bundle bundle = new Bundle();
                    bundle.putString("Voice_Path", mRecordPath);
                    Log.e("mRecordPath", mRecordPath);
                    setResult(011, Record.this.getIntent().putExtras(bundle));
                    finish();
                }
            }

        });
    }

    private void init() {
        mMINVolume = (int) TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP, 4.5f, getResources()
                        .getDisplayMetrics());
        mMAXVolume = (int) TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP, 65f, getResources()
                        .getDisplayMetrics());
    }

//    Handler mRecordHandler = new Handler() {
//
//        public void handleMessage(Message msg) {
//            super.handleMessage(msg);
//            switch (msg.what) {
//                case 0:
//                    if (mRecord_State == RECORD_ING) {
//                        mRecord_State = RECORD_ED;
//                        try {
//                            mRecordUtil.stop();
//                            mRecord_Volume = 0;
//                        } catch (IOException e) {
//                            e.printStackTrace();
//                        }
//
//                        mDisplayVoiceLayout.setVisibility(View.VISIBLE);
//                        mDisplayVoicePlay
//                                .setImageResource(R.drawable.globle_player_btn_play);
//                        mDisplayVoiceProgressBar.setMax((int) mRecord_Time);
//                        mDisplayVoiceProgressBar.setProgress(0);
//                        mDisplayVoiceTime.setText((int) mRecord_Time + "s");
//                    }
//                    break;
//
//                case 1:
//                    mDisplayVoiceProgressBar.setProgress((int) mRecord_Time);
//                    mDisplayVoiceTime.setText((int) mRecord_Time + "s");
//                    ViewGroup.LayoutParams params = mDisplayVoicePlay.getLayoutParams();
//                    if (mRecord_Volume < 200.0) {
//                        params.height = mMINVolume;
//                    } else if (mRecord_Volume > 200.0 && mRecord_Volume < 400) {
//                        params.height = mMINVolume * 2;
//                    } else if (mRecord_Volume > 400.0 && mRecord_Volume < 800) {
//                        params.height = mMINVolume * 3;
//                    } else if (mRecord_Volume > 800.0 && mRecord_Volume < 1600) {
//                        params.height = mMINVolume * 4;
//                    } else if (mRecord_Volume > 1600.0 && mRecord_Volume < 3200) {
//                        params.height = mMINVolume * 5;
//                    } else if (mRecord_Volume > 3200.0 && mRecord_Volume < 5000) {
//                        params.height = mMINVolume * 6;
//                    } else if (mRecord_Volume > 5000.0 && mRecord_Volume < 7000) {
//                        params.height = mMINVolume * 7;
//                    } else if (mRecord_Volume > 7000.0 && mRecord_Volume < 10000.0) {
//                        params.height = mMINVolume * 8;
//                    } else if (mRecord_Volume > 10000.0 && mRecord_Volume < 14000.0) {
//                        params.height = mMINVolume * 9;
//                    } else if (mRecord_Volume > 14000.0 && mRecord_Volume < 17000.0) {
//                        params.height = mMINVolume * 10;
//                    } else if (mRecord_Volume > 17000.0 && mRecord_Volume < 20000.0) {
//                        params.height = mMINVolume * 11;
//                    } else if (mRecord_Volume > 20000.0 && mRecord_Volume < 24000.0) {
//                        params.height = mMINVolume * 12;
//                    } else if (mRecord_Volume > 24000.0 && mRecord_Volume < 28000.0) {
//                        params.height = mMINVolume * 13;
//                    } else if (mRecord_Volume > 28000.0) {
//                        params.height = mMAXVolume;
//                    }
//
//                    break;
//            }
//        }
//
//    };
}
